<template>
  <div class="w-full h-full p-3 rounded-xl border-slate-200 bg-white">
    <div class="flex items-center  content-center  mb-2">
      <div class="flex items-center bg-indigo-50/60 rounded-lg py-0.5 px-2">
        <i class="iconfont icon-shishikucunshiyitu text-indigo-500 text-base"/>
        <span class="title font-semibold text-indigo-600 ml-1.5">{{ $t('inventoryInforSummary.outAndInBound') }}</span>
      </div>
      <div class="flex-1 h-[1px] bg-gradient-to-r from-indigo-200 via-indigo-100/50 to-transparent ml-3"></div>
      <el-form :inline="true" :model="from" class="align-center search-form" style="margin-bottom: 10px">
        <el-form-item class="label" :label="$t('iot.time')">
          <el-date-picker
            style="width: 220px" v-model="from.time" type="daterange"
            range-separator="-" :start-placeholder="$t('wms.startTime')" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
            :end-placeholder="$t('wms.endTime')" class="custom-date-picker"/>
        </el-form-item>
        <el-button icon="Search" class="buttons" size="small" type="primary" @click="getSerch" style="margin-top: 3px">
          {{ $t('wms.search') }}
        </el-button>
      </el-form>
    </div>
    <div class="w-full flex items-center mt-4" style="height: 90%;text-align: center">
      <div class="w-full h-full flex" style="border-radius: 16px;">
        <v-chart ref="currentRef2" class="w-full h-full"/>
      </div>
    </div>
  </div>
</template>
<script setup>
import '@/assets/font/iconfont.css'
import { getSemiTransferBarcodes, getTransferBarcodes } from '@/api/mes/allocationInforViewApi'
import useI18n from '@/hooks/language'
import { onMounted, reactive, ref } from 'vue'
import moment from 'moment'
import * as echarts from 'echarts'

const { t } = useI18n()
const data = reactive({
  current: 1,
  size: 999999
})
const from = reactive({
  time: [],
  warehouseCode: ''
})

const listOut = ref([])
const listBillsIn = ref([])
const listBillsOut = ref([])
const listIn = ref([])
const titleList = ref([])
const currentRef = ref(null)
const currentRef2 = ref(null)
const currentRef3 = ref(null)

const pieListOut = ref([
  { value: 0, name: 'YH', barcode: 0 },
  { value: 0, name: 'JC', barcode: 0 },
  { value: 0, name: 'LVT', barcode: 0 },
  { value: 0, name: 'LMHH', barcode: 0 },
  { value: 0, name: 'TH', barcode: 0 },
  { value: 0, name: 'JJG', barcode: 0 }])
const pieListIn = ref([
  { value: 0, name: 'YH', barcode: 0 },
  { value: 0, name: 'JC', barcode: 0 },
  { value: 0, name: 'LVT', barcode: 0 },
  { value: 0, name: 'LMHH', barcode: 0 },
  { value: 0, name: 'TH', barcode: 0 },
  { value: 0, name: 'JJG', barcode: 0 }])

const pieOption = () => {
  return {
    title: [
      {
        text: t('common.BringOut'),
        left: '25%',
        top: '42%',
        textAlign: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      {
        text: t('common.BringIn'),
        left: '75%',
        top: '42%',
        textAlign: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      }
    ],
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        const list = params.seriesName === t('common.BringOut') ? pieListOut.value : pieListIn.value
        const item = list.find(item => item.name === params.name)
        if (item) {
          return `
            <div style="padding: 8px;">
              <div style="display: flex; align-items: center; margin-bottom: 8px;">
                <span style="display: inline-block; width: 12px; height: 12px; border-radius: 50%; background-color: ${params.color}; margin-right: 8px;"></span>
                <span style="font-size: 14px; font-weight: bold; color: #333;">${params.name}</span>
              </div>
              <div style="display: flex; align-items: center; margin-bottom: 8px;">
                <span style="font-size: 14px; color: #666;">${params.seriesName}${t('wms.qty')} : <span style="color: #333; font-weight: bold;">${item.value}</span></span>
              </div>
              <div style="display: flex; align-items: center;">
                <span style="font-size: 14px; color: #666;">${t('common.barcodesNo')} : <span style="color: #333; font-weight: bold;">${item.barcode}</span></span>
              </div>
            </div>
          `
        }
        return ''
      },
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ccc',
      borderWidth: 1,
      padding: 0,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      bottom: '5%',
      data: pieListOut.value.map(item => item.name),
      textStyle: {
        fontSize: 12,
        fontWeight: 'bold'
      }
    },
    grid: {
      left: '10%',
      right: '10%',
      top: '5%',
      containLabel: true
    },
    series: [
      {
        name: t('common.BringOut'),
        type: 'pie',
        radius: ['15%', '60%'],
        center: ['25%', '45%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: function(params) {
            return [
              `{name|${params.name}}`,
              `{value|${params.value}}`
            ].join('\n');
          },
          rich: {
            name: {
              fontSize: 12,
              lineHeight: 20,
              align: 'center',
              fontWeight: 'bold'
            },
            value: {
              fontSize: 12,
              lineHeight: 20,
              align: 'center',
              fontWeight: 'bold',
              color: '#999'
            }
          },
          position: 'outside',
          distanceToLabelLine: 5
        },
        labelLayout: function (params) {
          // 判断标签矩形是否位于图表左半部分
          const isLeft = params.labelRect.x < currentRef2.value.getWidth() / 2;
          // 获取标签线的三个关键点坐标
          const points = params.labelLinePoints;
          // 更新标签线的终点坐标
          points[2][0] = isLeft
            ? params.labelRect.x
            : params.labelRect.x + params.labelRect.width;
          // 返回更新后的标签线关键点坐标
          return {
            labelLinePoints: points
          };
        },
        data: pieListOut.value
      },
      {
        name: t('common.BringIn'),
        type: 'pie',
        radius: ['15%', '60%'],
        center: ['75%', '45%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: function(params) {
            return [
              `{name|${params.name}}`,
              `{value|${params.value}}`
            ].join('\n');
          },
          rich: {
            name: {
              fontSize: 12,
              lineHeight: 20,
              align: 'center',
              fontWeight: 'bold'
            },
            value: {
              fontSize: 12,
              lineHeight: 20,
              align: 'center',
              fontWeight: 'bold',
              color: '#999'
            }
          },
          position: 'outside',
          distanceToLabelLine: 5
        },
        labelLayout: function (params) {
          // 判断标签矩形是否位于图表左半部分
          const isLeft = params.labelRect.x < currentRef2.value.getWidth() / 2;
          // 获取标签线的三个关键点坐标
          const points = params.labelLinePoints;
          // 更新标签线的终点坐标
          points[2][0] = isLeft
            ? params.labelRect.x
            : params.labelRect.x + params.labelRect.width;
          // 返回更新后的标签线关键点坐标
          return {
            labelLinePoints: points
          };
        },
        data: pieListIn.value
      }
    ]
  }
}

const getDefaultDateRange = () => {
  const start = moment().subtract(7, 'days').format('YYYY-MM-DD')// 本月一号
  const end = moment().format('YYYY-MM-DD') // 今天
  from.time = [start, end]
}

onMounted(async () => {
  await getDefaultDateRange()
  await transferBarcodes()
  if (currentRef2.value) {
    currentRef2.value.setOption(pieOption())
  } else {
    setTimeout(() => {
      if (currentRef2.value) {
        currentRef2.value.setOption(pieOption())
      }
    }, 100)
  }
})

const transferBarcodes = async () => {
  await getTransferBarcodes({
    startTime: from.time[0],
    endTime: from.time[1],
    warehouseCode: from.warehouseCode,
    current: data.current,
    size: data.size
  }).then(res => {
    if (res.code == 0) {
      titleList.value = ['YH', 'JC', 'LVT', 'LMHH', 'TH', 'JJG']
      listIn.value = []
      listOut.value = []
      listBillsIn.value = []
      listBillsOut.value = []
      // 动态添加仓库 过滤掉 FG 和 RM 仓库
      // const filteredRecords = res.data.list.records.filter(item => item.warehouCode !== 'FG' && item.warehouCode !== 'RM')
      // const filteredInAndOutList = res.data.inAndOutList?.filter(item => item.warehouseCode !== 'FG' && item.warehouseCode !== 'RM')
      //
      // filteredRecords.forEach(item => {
      //   // 将所有仓库添加到titleList里面并去重
      //   if (titleList.value.indexOf(item.warehouCode) === -1) {
      //     titleList.value.push(item.warehouCode)
      //   }
      // })
      // filteredInAndOutList?.forEach(item => {
      //   // 将所有仓库添加到titleList里面并去重
      //   if (titleList.value.indexOf(item.warehouseCode) === -1 ) {
      //     titleList.value.push(item.warehouseCode)
      //   }
      // })

      // 柱状图和折现图用的数据
      titleList.value.forEach(item => {
        // 条码数
        let a = res.data.inAndOutList?.filter(i => i.warehouseCode === item.name)[0]?.transferInCount || 0
        let b = res.data.inAndOutList?.filter(i => i.warehouseCode === item.name)[0]?.transferOutCount || 0
        // 数量
        let c = res.data.list.records.filter(i => i.warehouCode === item.name && i.transFer === '调入').reduce((sum, record) => sum + (record.qty || 0), 0)
        let d = res.data.list.records.filter(i => i.warehouCode === item.name && i.transFer === '调出').reduce((sum, record) => sum + (record.qty || 0), 0)
        listIn.value.push(a)
        listOut.value.push(b)
        listBillsIn.value.push(c > 0 ? c.toFixed(2) : 0)
        listBillsOut.value.push(d > 0 ? c.toFixed(2) : 0)
      })

      // 玫瑰图用的数据
      pieListOut.value.forEach(item => {
        let b = res.data.inAndOutList?.filter(i => i.warehouseCode === item.name)[0]?.transferOutCount || 0
        let d = res.data.list.records.filter(i => i.warehouCode === item.name && i.transFer === '调出').reduce((sum, record) => sum + (record.qty || 0), 0)
        item.value = d > 0 ? d.toFixed(2) : 0
        item.barcode = b
      })
      pieListIn.value.forEach(item => {
        let a = res.data.inAndOutList?.filter(i => i.warehouseCode === item.name)[0]?.transferInCount || 0
        let c = res.data.list.records.filter(i => i.warehouCode === item.name && i.transFer === '调入').reduce((sum, record) => sum + (record.qty || 0), 0)
        item.value = c > 0 ? c.toFixed(2) : 0
        item.barcode = a
      })
    }
  })
}

const getSerch = async () => {
  await transferBarcodes()
  if (currentRef2.value) {
    currentRef2.value.setOption(pieOption())
  } else {
    setTimeout(() => {
      if (currentRef2.value) {
        currentRef2.value.setOption(pieOption())
      }
    }, 100)
  }
}
</script>
<style scoped lang="scss">

</style>
